import { getUserIofoAPI, loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  saveToken(state, payload) {
    state.token = payload
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  }

}

const actions = {
  async loginAction(store, payload) {
    const res = await loginAPI(payload)
    // 存储token
    store.commit('saveToken', res)
    setToken(res)
    router.push('/')
    Message({
      message: '登录成功',
      type: 'success',
      duration: 5 * 1000
    })
  },

  // get user info
  async getUserIofo(store) {
    const res = await getUserIofoAPI()

    store.commit('setUserInfo', res)
  },
  // user logout
  logout({ commit }) {
    setToken('')
    commit('saveToken', '')
    commit('setUserInfo', {})
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

